﻿//===============================================================================
// Apolineo Patterns & Practices LeanEngine Framework
//===============================================================================
// Copyright © Apolineo Desenvolvimento de Sistemas Ltda.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================

using System;
using System.ComponentModel;
using System.Windows.Forms;
using LeanEngine.Entity;
using LeanEngine.Extensions;
using LeanEngine.Collections;
using LeanEngine.SalesConcept.Business;
using LeanEngine.SalesConcept.Entity;

namespace LeanEngine.SalesConcept.Windows.Control
{
    public partial class SearchControlOfSale : UserControl
    {
        #region Declaration Members

        [Category("Action")]
        public event Action AddNewSale;
        [Category("Action")]
        public event Action<Sale> UpdateSale;
        [Category("Action")]
        public event Action<long> DeleteSale;

        private int _selectedRowIndex;

        #endregion

        #region Constructor Members

        public SearchControlOfSale()
        {
            InitializeComponent();

            this.selProduct.FormSelect = new FormSelectProduct();
            this.selSalesman.FormSelect = new FormSelectSalesman();
            this.selCustomer.FormSelect = new FormSelectCustomer();

            this.dataGridView1.AutoGenerateColumns = false;
            this.bindingNavigatorAddNewItem.Enabled = true;

            this.dtpBegin.Value = DateTime.Now.Date.AddMonths(-1);
            this.dtpEnd.Value = DateTime.Now.Date;
        }

        #endregion

        #region Property Members

        private PagedList<Sale> CurrentPagedResultList { get; set; }

        [Category("Behavior")]
        [Description("Show or hide the button of add new Sale.")]
        public bool AddNewButtonVisible
        {
            get { return bindingNavigatorAddNewItem.Visible; }
            set { bindingNavigatorAddNewItem.Visible = value; }
        }

        [Category("Behavior")]
        [Description("Show or hide the button of delete the selected Sale.")]
        public bool DeleteButtonVisible
        {
            get { return bindingNavigatorDeleteItem.Visible; }
            set { bindingNavigatorDeleteItem.Visible = value; }
        }

        #endregion

        #region Method Members

        private void UpdateNavigator(int currentPageIndex)
        {
            bindingNavigatorMoveFirstItem.Enabled = (currentPageIndex.IsGreaterThan(0));
            bindingNavigatorMoveLastItem.Enabled = (currentPageIndex.IsLessThan(this.CurrentPagedResultList.PageCount));
            bindingNavigatorMoveNextItem.Enabled = (currentPageIndex.IsLessThan(this.CurrentPagedResultList.PageCount));
            bindingNavigatorMovePreviousItem.Enabled = (currentPageIndex.IsGreaterThan(0));
        }

        private void UpdateBindPage(int pageIndex)
        {
            if (pageIndex.IsLessThan(0)) pageIndex = 0;
            else if (pageIndex.IsGreaterThan(GetMaxPageIndex()) && GetMaxPageIndex().IsGreaterThanEqual(0)) pageIndex = GetMaxPageIndex();

            var criteria = new SaleSearchCriteria()
            {
                PageIndex = pageIndex,
                PageSize = 25,
                BeginDate = this.dtpBegin.Value,
                EndDate = this.dtpEnd.Value,
                CustomerId = this.selCustomer.SelectedValue.IsNotNull() ? (this.selCustomer.SelectedValue as Customer).Id : 0,
                SalesmanId = this.selSalesman.SelectedValue.IsNotNull() ? (this.selSalesman.SelectedValue as Salesman).Id : 0,
                ProductId = this.selProduct.SelectedValue.IsNotNull() ? (this.selProduct.SelectedValue as Product).Id : 0,
            };

            this.CurrentPagedResultList = new SaleBusinessFacade(Program.LoginToken).ListSaleBySaleCriteria(criteria);

            dataGridView1.DataSource = null;
            dataGridView1.DataSource = this.CurrentPagedResultList.Items;

            bindingNavigator1.PositionItem.Text = (pageIndex + 1).ToString();
            bindingNavigator1.CountItem.Text = "de " + (this.CurrentPagedResultList.PageCount + 1).ToString();
        }

        private int GetMaxPageIndex()
        {
            var pageCount = bindingNavigatorCountItem.Text.Replace("de", string.Empty).Trim();
            return pageCount.ToInt32();
        }

        private int GetCurrentPageIndex()
        {
            return bindingNavigatorPositionItem.Text.IsNumeric() ? bindingNavigatorPositionItem.Text.ToInt32() : 0;
        }

        protected virtual void OnAddNewSale()
        {
            if (this.AddNewSale.IsNotNull())
            {
                this.AddNewSale.Invoke();
            }
        }

        protected virtual void OnUpdateSale(Sale value)
        {
            if (this.UpdateSale.IsNotNull())
            {
                this.UpdateSale.Invoke(value);
            }
        }

        protected virtual void OnDeleteSale(long key)
        {
            if (this.DeleteSale.IsNotNull())
            {
                this.DeleteSale.Invoke(key);
            }
            else
            {
                new SaleBusinessFacade(Program.LoginToken).DeleteSaleById(key);
                var pageIndex = GetCurrentPageIndex();

                if ((this.CurrentPagedResultList.Items.Count - 1).IsLessThan(1))
                {
                    pageIndex -= 1;
                    if (pageIndex.IsLessThan(0)) pageIndex = 0;
                }

                UpdateBindPage(pageIndex);
            }
        }

        #endregion

        #region Event Members

        private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            string value = string.Empty;

            if (this.dataGridView1.Columns[e.ColumnIndex] == colCustomer)
            {
                value = this.CurrentPagedResultList.Items[e.RowIndex].Customer.Name;
            }
            else if (this.dataGridView1.Columns[e.ColumnIndex] == colSalesman)
            {
                value = this.CurrentPagedResultList.Items[e.RowIndex].Salesman.Name;
            }

            this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = value;
            e.Cancel = true;
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                if (this._selectedRowIndex.IsGreaterThanEqual(0) &&
                    this.CurrentPagedResultList.Items.Count.IsGreaterThan(this._selectedRowIndex))
                {
                    var value = this.CurrentPagedResultList.Items[this._selectedRowIndex];
                    OnUpdateSale(value);
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void bindingNavigatorMoveFirstItem_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                UpdateBindPage(0);
                UpdateNavigator(0);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void bindingNavigatorMovePreviousItem_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                var currentPageIndex = GetCurrentPageIndex();
                UpdateBindPage(--currentPageIndex);
                UpdateNavigator(currentPageIndex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void bindingNavigatorMoveNextItem_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                var currentPageIndex = GetCurrentPageIndex();
                UpdateBindPage(++currentPageIndex);
                UpdateNavigator(currentPageIndex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void bindingNavigatorMoveLastItem_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                UpdateBindPage(GetMaxPageIndex());
                UpdateNavigator(GetMaxPageIndex());
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                OnAddNewSale();
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                var key = this.CurrentPagedResultList.Items[dataGridView1.SelectedRows[0].Index].Id;
                OnDeleteSale(key);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                UpdateBindPage(0);
                UpdateNavigator(0);
                if (this.CurrentPagedResultList.TotalItems == 0)
                {
                    MessageBox.Show("Nenhum produto encontrado com os parametros informados.", this.Parent.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            _selectedRowIndex = e.RowIndex;
            bindingNavigatorDeleteItem.Enabled = _selectedRowIndex.IsGreaterThanEqual(0);
        }

        #endregion
    }
}
